package com.sxfq.loansupermarket.backsystem.modular.weixin;

import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.node.MenuNode;
import com.sxfq.loansupermarket.backsystem.common.persistence.dao.UserMapper;
import com.sxfq.loansupermarket.backsystem.common.persistence.model.Dept;
import com.sxfq.loansupermarket.backsystem.common.persistence.model.User;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroUser;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.system.dao.MenuDao;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 登录控制器
 *
 * @author fengshuonan
 * @Date 2017年1月10日 下午8:25:24
 */
@Controller
@RequestMapping("/weixin")
public class WeixinLoginController extends BaseController {
    @Autowired
    MenuDao menuDao;

    @Autowired
    UserMapper userMapper;

    @Autowired
    private SqlMapper sqlMapper;

    private String PREFIX = "/weixin/";

    /**
     * 跳转到主页
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(Model model) {
        List<Integer> roleList = ShiroKit.getUser().getRoleList();  //获取菜单列表
        if (roleList == null || roleList.size() == 0) {
            ShiroKit.getSubject().logout();
            String tips="该用户没有角色，无法登陆";
            ShiroKit.setSessionAttr("tips",tips);
            return PREFIX + "login.html";
        }
        List<MenuNode> menus = menuDao.getMenusByRoleIds(roleList);
        List<MenuNode> titles = MenuNode.buildTitle(menus);
        ShiroKit.setSessionAttr("titles",titles);
        model.addAttribute("titles", titles);
        return PREFIX + "index.html";
    }

    /**
     * 跳转到主页
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String to_index(Model model) {
        String tips="";
        String sql = "select t.simplename,t.abbreviation,t.province,t.cities,t.address,t.phone,t.auditswitch,t.auditOfDept," +
                "CONCAT(sttle_accounts_hour,':',sttle_accounts_minute,':',sttle_accounts_second) as sttleAccountsHour " +
                " from dept t where t.simplename= '" + ShiroKit.getSessionAttr("outpatientName") + "'";
        Dept dept = sqlMapper.selectOne(sql, Dept.class);
        String sqluser = "select b.simplename as name,a.avatar as avatar,a.account as account,c.name as roleName," +
                " a.audit_node as auditNode,a.register_is_ring as registerIsRing " +
                " from user a left join dept b on a.deptId like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                " where a.account='" + ShiroKit.getSessionAttr("username") + "' and b.simplename= '" + ShiroKit.getSessionAttr("outpatientName") + "'";
        User user = sqlMapper.selectOne(sqluser, User.class);
        if (user != null) {

        } else {
            String sqluser1 = "select b.simplename as name,a.avatar as avatar,a.account as account,c.name as roleName," +
                    " a.audit_node as auditNode,a.register_is_ring as registerIsRing " +
                    " from user a left join dept b on a.deptId like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where a.account='" + ShiroKit.getSessionAttr("username") + "'  and b.simplename like '%总公司%'";
            User user1 = sqlMapper.selectOne(sqluser1, User.class);
            if (user1 != null) {
                if (user1.getName().indexOf("总公司")!=-1) {
                    user = user1;
                }
            } else {
                tips = "该用户没有权限登陆该诊所";
                ShiroKit.setSessionAttr("tips", tips);
                model.addAttribute("tips", ShiroKit.getSessionAttr("tips"));
                model.addAttribute("username", ShiroKit.getSessionAttr("username"));
                model.addAttribute("password", ShiroKit.getSessionAttr("password"));
                model.addAttribute("outpatientName", ShiroKit.getSessionAttr("outpatientName"));
                return "/login.html";
            }
        }
        List<Integer> roleList = ShiroKit.getUser().getRoleList();  //获取菜单列表
        if (roleList == null || roleList.size() == 0) {
            ShiroKit.getSubject().logout();
            tips="该用户没有角色，无法登陆";
            ShiroKit.setSessionAttr("tips",tips);
            model.addAttribute("tips", ShiroKit.getSessionAttr("tips"));
            return PREFIX + "login.html";
        }
        ShiroKit.getUser().setAvatar(user.getAvatar());
        ShiroKit.setSessionAttr("abbreviation",dept.getAbbreviation());
        ShiroKit.setSessionAttr("auditOfDept",dept.getAuditofdept());
        ShiroKit.setSessionAttr("auditswitch",dept.getAuditswitch());
        ShiroKit.setSessionAttr("province",dept.getProvince());
        ShiroKit.setSessionAttr("cities",dept.getCities());
        ShiroKit.setSessionAttr("address",dept.getAddress());
        ShiroKit.setSessionAttr("phone",dept.getPhone());
        ShiroKit.setSessionAttr("sttleAccountsTime",dept.getSttleAccountsHour());
        model.addAttribute("tips", ShiroKit.getSessionAttr("tips"));
        model.addAttribute("abbreviation", ShiroKit.getSessionAttr("abbreviation"));
        model.addAttribute("outpatientName", ShiroKit.getSessionAttr("outpatientName"));
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        model.addAttribute("avatar", ShiroKit.getUser().getAvatar()); //用户头像
        model.addAttribute("passWord", ShiroKit.getSessionAttr("password"));
        model.addAttribute("titles", ShiroKit.getSessionAttr("titles"));
        tips="登录成功";
        ShiroKit.setSessionAttr("tips",tips);
        return PREFIX + "index.html";
    }

    //得到子集
    @RequestMapping(value = "/getChildrenValue", method = RequestMethod.POST)
    @ResponseBody
    public List<MenuNode> getChildrenValue(String code, HttpServletResponse response) {
        String sql="select b.name as name,b.url as url from role a left join relation c on a.id=c.roleid " +
                " left join menu b on c.menuid=b.id left join user d on a.id=d.roleid " +
                " where d.account='"+ ShiroKit.getUser().getAccount()+"' " +
                " and pcode='"+code+"' and b.ismenu=1 order by b.num";
        List<MenuNode> menuNodes =sqlMapper.selectList(sql, MenuNode.class);
        return menuNodes;
    }

    /**
     * 跳转到登录页面
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(Model model, HttpServletResponse response) {
        String tableHead = ShiroKit.getSessionAttr("abbreviation");
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("tips", ShiroKit.getSessionAttr("tips"));
        return PREFIX + "login.html";
    }

    /**
     * 点击登录执行的动作
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String loginVali(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        ShiroKit.setSessionAttr("tips","");
        String username = super.getPara("username").trim();
        String password = super.getPara("password").trim();
        String outpatientName = super.getPara("outpatientName").trim();
        Subject currentUser = ShiroKit.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password.toCharArray());
        token.setRememberMe(true);
        currentUser.login(token);
        ShiroUser shiroUser = ShiroKit.getUser();
        super.getSession().setAttribute("shiroUser", shiroUser);
        super.getSession().setAttribute("username", shiroUser.getAccount());
        LogManager.me().executeLog(LogTaskFactory.loginLog(shiroUser.getId(), HttpKit.getIp()));
        ShiroKit.getSession().setAttribute("sessionFlag", true);
        ShiroKit.setSessionAttr("outpatientName", outpatientName);
        ShiroKit.setSessionAttr("username", username);
        ShiroKit.setSessionAttr("password", password);
        return  REDIRECT + PREFIX+"/";
    }

    /**
     * 退出登录
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logOut() {
        LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
        ShiroKit.getSubject().logout();
        return  REDIRECT +PREFIX+ "/login";
    }
}